package com.example.sys.job.init;

import com.example.core.init.AbstractSysInitService;
import com.example.sys.job.annotation.JobScope;
import com.example.sys.job.po.SysJob;
import com.example.sys.job.service.SysJobService;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class SysInitJobServiceImpl extends AbstractSysInitService {

    @Override
    public void init() throws Exception {
        SysJobService sysJobService = getApplicationContext().getBean(SysJobService.class);
        Map<String, Object> beanMaps = getApplicationContext().getBeansWithAnnotation(JobScope.class);
        for (Object o : beanMaps.values()) {
            JobScope jobScope = o.getClass().getAnnotation(JobScope.class);
            SysJob sysJob = sysJobService.getByJobClass(o.getClass().getName());
            if (sysJob == null) {
                sysJob = new SysJob();
                sysJob.setName(jobScope.name());
                sysJob.setJobClass(o.getClass().getName());
                sysJob.setCron(jobScope.cron());
                sysJob.setEnabled(true);
                sysJob.setContext(jobScope.desc());
                sysJob.recalculateFields();
                sysJobService.save(sysJob);
                sysJobService.addJob(sysJob);
            }
        }
    }

    @Override
    public void start() throws Exception {

    }

    @Override
    public void destroy() throws Exception {

    }
}
